import { BeanDefine, BeanPostProcessor, Component } from 'j-spring';

let socketHandlers: SocketHandler<any, any>[] = [];

export interface SocketHandler<SocketType, IoType> {
  getHandlerName(): string;
  registerEvent(socket: SocketType, io: IoType): Promise<void>;
  isSocketHandler(): boolean;
  isAutoRegister(): boolean;
}

@Component()
export class SocketHandlerPostProcessor implements BeanPostProcessor {
  getSort(): number {
    return 1000;
  }
  postProcessBeforeInitialization(bean: any, _beanDefine: BeanDefine): Object {
    return bean;
  }
  postProcessAfterInitialization(bean: any, _beanDefine: BeanDefine): Object {
    if (bean.registerEvent && bean.isSocketHandler && bean.isSocketHandler()) {
      socketHandlers.push(bean);
    }
    return bean;
  }
}

export const getSocketHandler = () => socketHandlers;
